package cn.codergege.demo.controller

import cn.codergege.demo.entity.Person
import cn.codergege.demo.service.PersonService
import org.slf4j.LoggerFactory
import org.springframework.batch.core.Job
import org.springframework.batch.core.JobParametersBuilder
import org.springframework.batch.core.launch.JobLauncher
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
class HelloController {
    private val log = LoggerFactory.getLogger(javaClass)

    @Autowired
    lateinit var jobLauncher: JobLauncher
    @Autowired
    @Qualifier("csv2MysqlPersonJob")
    lateinit var job: Job
    @Autowired
    @Qualifier("mysql2CsvPersonJob")
    lateinit var mysql2CsvPersonJob: Job

//    @Autowired
//    lateinit var fileJobLauncher: JobLauncher
    @Autowired
    @Qualifier("csv2CsvPersonJob")
    lateinit var csv2csvPersonJob: Job

    @Autowired
    lateinit var personService: PersonService

    @GetMapping("/mysql2csv")
    fun mysql2csv(): String {
        // 这里硬编码了
        val sqlParamName = "%*%"
        jobLauncher.run(
            mysql2CsvPersonJob,
            JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .addString("sqlParamName", sqlParamName)
                .toJobParameters()
        )

        return "完成"
    }
    @GetMapping("/csv2csv")
    fun csv2csv(): String {
        // 这里硬编码一下，模拟从页面获取文件路径, 而输出路径就写在配置文件中了
        val path = "f:/tmp/person.csv"

        jobLauncher.run(
            csv2csvPersonJob
            , JobParametersBuilder()
            .addLong("time", System.currentTimeMillis())
            .addString("path2File", path)
            .toJobParameters()
        )
        return "完成"
    }

    @GetMapping("/imp")
    fun imp(@RequestParam(required = false) path2File: String?): String {
        // 这里硬编码一下，模拟从页面获取文件路径
        val path = "f:/tmp/person.csv"
        jobLauncher.run(job, JobParametersBuilder()
            .addLong("time", System.currentTimeMillis())
            .addString("path2File", path)
            .toJobParameters())
        return "Ok"
    }

    @GetMapping(*arrayOf("/hello", "/hi"))
    fun hello(): Any? {
        log.info("Hello world! ...")
        val persons = personService.findPersonsByGender(1)
        persons?.forEach(::println)
        return persons
    }

    @GetMapping("/person/{id}")
    fun getPerson(@PathVariable("id") id: Int): Person {
        return personService.findPersonById(id)
    }
}
